package com.jiang.readline.Utils;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

@Component
public class CountCodeLinesUtils {

    public static int CodeLines(String filePath) {
        int count = 0;
        boolean inComment = false; // 是否在注释中
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (inComment) {
                    if (line.endsWith("*/")) {    //这是注释的结尾 所以判断为false
                        inComment = false;
                    }
                } else {
                    if (line.startsWith("/*")) {
                        inComment = true;      //注释开始，判断为true
                    } else if (!line.startsWith("//") && !line.isEmpty()) { // 不是单行注释和空白行
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count;
    }

    public static int CodeLinesForRuby(String filePath) {
        int count = 0;
        boolean inComment = false; // 是否在注释中
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (inComment) {
                    if (line.endsWith("=end")) {    //这是注释的结尾 所以判断为false
                        inComment = false;
                    }
                } else {
                    if (line.startsWith("=begin")) {    //注释开始，判断为true
                        inComment = true;
                    } else if (!line.startsWith("##") && !line.isEmpty()) { // 不是单行注释和空白行
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count;
    }
}
